package com.wx.lock.zooKeeper;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @ClassName AbstractZookeeper
 * @Author wx
 * @Description Zookeeper客户端
 * @Date 2018-11-28-21:17
 */
public class ZookeeperClient implements Watcher{
    private ZooKeeper zk;
    public final int SESSION_TIMEOUT = 10000;
    public static final String GROUP_PATH = "/disLocks";
    public final String ZK_ADDRESS = "127.0.0.1:2181";
    private final CountDownLatch latch = new CountDownLatch(1);
    
    /**
     * @methodName: coonect
     * @author: wx
     * @description: 连接初始化
     * @date: 2018/11/28
     * @return: org.apache.zookeeper.ZooKeeper
     */
    public ZooKeeper coonect(){
        // 连接zookeeper

        try {
            zk = new ZooKeeper(ZK_ADDRESS, SESSION_TIMEOUT, this);
            //进行阻塞
            latch.await();
            //创建父节点
            if (zk.exists(GROUP_PATH, false) == null) {
                //创建无需权限并持久化父节点
                zk.create(GROUP_PATH, "创建父节点".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("zk连接失败");
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException("阻塞中断异常");
        } catch (KeeperException e) {
            e.printStackTrace();
            throw new RuntimeException("创建父节点失败");
        }
        return  zk;

    }


    @Override
    public void process(WatchedEvent watchedEvent) {
        //如果是建立连接
        if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
            //如果建立连接成功，则发送信号量，让后续阻塞程序向下执行
            latch.countDown();
            System.out.println("zk 建立连接");
        }
    }


}
